import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken,clearAll } from '@/utils/myAuth'
import router from '@/router';

// create an axios instance
const service = axios.create({
  baseURL: "http://leju.bufan.cloud", // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

//请求前的打断函数
service.interceptors.request.use(
  config => {
    const token = getToken()
    if(token){
      console.log(config);
      config.headers['token'] = token
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
 
  response => {
    const res = response.data
    if(res.code === 20002){
            clearAll()
            router.push("/login")
        }
      return res 
    
  },
  
  error => {
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

// function http(apiRequest){
//  console.log(apiRequest)
//  var obj ={
//    method:apiRequest.method,
//    headers:{},
//    url:apiRequest.url
//  }
//  if(Object.keys(apiRequest.data).length>0){
//    console.log(Object.keys(apiRequest.data))
//    if(apiRequest.method=='POST'){
//     obj.data = apiRequest.data
//    }else {
//     obj.params = apiRequest.data
//    }
//  }
//  obj.headers['Content-Type'] = 'application/json'
//  console.log(obj)
//  return service(obj)
// }

export default service
